// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import GIFSprite from "../lib/gif/GIFSprite"
import config from "../config";
import * as Util from "../util";
import global from "../global";
import playerInfoNode from "../ui/playerInfoNode";

import { GIFCache } from "../lib/gif/GIF";
const { ccclass, property } = cc._decorator;

@ccclass
export default class Home extends cc.Component {

    // @property(cc.Label)
    // gameName: cc.Label = null;

    @property(playerInfoNode)
    playerNode: playerInfoNode = null;

    @property({
        type: cc.Sprite,
        tooltip: "soundImg",
    })
    soundImg: cc.Sprite = null;

    @property({
        type: cc.Button,
        tooltip: "Start",
    })
    startGameButton: cc.Button = null;

    @property({
        type: cc.Button,
        tooltip: "leaderboard",
    })
    leaderboardButton: cc.Button = null;

    // @property({
    //     type: GIFSprite,
    //     tooltip: "introGIF...",
    //     displayName: "introGIF",
    // })
    // introduceGif: GIFSprite = null;

    @property({
        type: cc.Sprite,
        tooltip: "background",
        displayName: "background",
    })
    background: cc.Sprite = null;

    @property({
        type: cc.Sprite,
        tooltip: "instruction1",
        displayName: "instruction1",
    })
    instruction1: cc.Sprite = null;

    @property({
        type: cc.Sprite,
        tooltip: "instruction2",
        displayName: "instruction2",
    })
    instruction2: cc.Sprite = null;

    @property({
        type: cc.Sprite,
        tooltip: "instruction3",
        displayName: "instruction3",
    })
    instruction3: cc.Sprite = null;

    @property({
        type: cc.Sprite,
        tooltip: "instruction4",
        displayName: "instruction4",
    })
    instruction4: cc.Sprite = null;

    @property({
        type: cc.Sprite,
        tooltip: "instruction5",
        displayName: "instruction5",
    })
    instruction5: cc.Sprite = null;

    @property({
        type: cc.Sprite,
        tooltip: "instruction6",
        displayName: "instruction6",
    })
    instruction6: cc.Sprite = null;

    @property({
        type: cc.Node,
        displayName: "Chooce Game mode",
        tooltip: "选择游戏界面"
    })
    chooseMode: cc.Node = null;

    @property({
        type: cc.Node,
        displayName: "Chooce Level",
        tooltip: "选择关卡"
    })
    levelChoosePopWindow: cc.Node = null;

    @property({
        type: cc.Prefab,
        displayName: "Chooce Level Button Prefab",
        tooltip: "选择关卡按钮模板"
    })
    levelChoosePrefab: cc.Prefab = null;
    // LIFE-CYCLE CALLBACKS:

    public wxPlayerInfo: PlayerInfos = null;
    public isAuth = null;

    private tapaudio: cc.AudioClip = null;
    private mainmusicaudio: cc.AudioClip = null;

    public breakModeButton: cc.Button = null;
    public competeSpeedModeButton: cc.Button = null;
    public returnHomeButton: cc.Button = null;

    public chooseLayout: cc.Layout = null;
    public backToChooseModeButton: cc.Button = null;


    onLoad() {
        this.initHome();
        // Util.preloadAllResources();
    }

    start() {
        this.setListener();
    }

    update(dt) {


    }

    initHome(){
        [this.breakModeButton, this.competeSpeedModeButton, this.returnHomeButton] = this.chooseMode.getComponentsInChildren(cc.Button);
        this.chooseMode.active = false;

        this.chooseLayout = this.levelChoosePopWindow.getComponentInChildren(cc.Layout);
        this.backToChooseModeButton = this.levelChoosePopWindow.getComponentInChildren(cc.Button);
        this.levelChoosePopWindow.active = false;

        // console.log("start!!!");

        cc.resources.load('Audio/main/bgm', cc.AudioClip, (err, audioClip) => {
            this.mainmusicaudio = audioClip;
            if (this.mainmusicaudio) cc.audioEngine.playMusic(this.mainmusicaudio, true);
        })

        cc.resources.load('Audio/main/tap', cc.AudioClip, (err, audioClip) => {
            this.tapaudio = audioClip;
        })

        // cc.assetManager.loadRemote(config.HomeMusicURL, { ext: '.mp3' }, (err, audioClip) => {
        //     this.mainmusicaudio = audioClip;
        //     if (this.mainmusicaudio) cc.audioEngine.playMusic(this.mainmusicaudio, true);
        // })

        // cc.assetManager.loadRemote(config.HomeTapSoundURL, { ext: '.mp3' }, (err, audioClip) => {
        //     this.tapaudio = audioClip;
        // })

        // this.setPhoto(config.backgroundURL, this.background, '.png');
        // this.setPhoto(config.ins1URL, this.instruction1, '.png');
        // this.setPhoto(config.ins2URL, this.instruction2, '.png');
        // this.setPhoto(config.ins3URL, this.instruction3, '.png');
        // this.setPhoto(config.ins4URL, this.instruction4, '.png');
        // this.setPhoto(config.ins5URL, this.instruction5, '.png');
        // this.setPhoto(config.ins6URL, this.instruction6, '.png');

        this.enableShareButton();
        // GIFCache.getInstance();
        // let path:string = "https://n.sinaimg.cn/tech/transform/362/w150h212/20200818/3a1c-ixvrvsp6661075.gif"
        // this.introduceGif.setInnerPath(path);

        this.buttonOff();
        let phoneSize = cc.view.getFrameSize()
        if (!config.isTest) { // 非测试状态下获取权限
            // console.log(this.node);
            if (!!global.player) {
                !!this.playerNode && this.playerNode.loadingInfo() //.getInfo(global.player);
                this.buttonOn();
                Util.initCloud();
            }
            else {
                getPlayerInfo({ width: phoneSize.width, height: phoneSize.height });
            }
        }
        else {
            this.buttonOn();
        }
        // console.log(this.mainmusicaudio);
        cc.audioEngine.setMusicVolume(0.6);
        if (this.mainmusicaudio) cc.audioEngine.playMusic(this.mainmusicaudio, true);

    }

    /**
     * 给按键绑定函数
     */
    setListener(){
        this.startGameButton && this.startGameButton.node.on(cc.Node.EventType.TOUCH_START, () => this.loadGameMenu());
        this.leaderboardButton && this.leaderboardButton.node.on(cc.Node.EventType.TOUCH_START, () => this.loadLRScene());
        this.breakModeButton && this.breakModeButton.node.on(cc.Node.EventType.TOUCH_START, (event) => { this.breakMode() });
        this.competeSpeedModeButton && this.competeSpeedModeButton.node.on(cc.Node.EventType.TOUCH_START, (event) => { this.competeSpeedMode() });
        this.returnHomeButton && this.returnHomeButton.node.on(cc.Node.EventType.TOUCH_START, (event) => { this.returnHomeInMenu() });
        this.backToChooseModeButton && this.backToChooseModeButton.node.on(cc.Node.EventType.TOUCH_START, (event) => { this.backToChooseMode() });
    }

    loadGameMenu() {//进入选关菜单
        this.chooseMode.active = true;
    }
    // 切换到游戏场景
    // 闯关模式
    returnHomeInMenu() {
        // cc.audioEngine.stopMusic();
        if (this.tapaudio) cc.audioEngine.playEffect(this.tapaudio, false);
        this.chooseMode.active = false;
    }

    breakMode() {
        if (this.tapaudio) cc.audioEngine.playEffect(this.tapaudio, false);
        this.chooseMode.active = false;
        if (global.maxBreakingLevel < 0) {
            Util.getCloudBreaking((res) => {
                if (res.data.length == 0) {
                    global.maxBreakingLevel = 0;
                    Util.updataCloudBreaking(0);
                }
                else {
                    global.maxBreakingLevel = res.data.breakLevel;
                }
                this.setChooseLevelView();
            })
        }
        else {
            this.setChooseLevelView();
        }

        // cc.audioEngine.stopMusic();
        // cc.director.loadScene("Game");
    }

    backToChooseMode() {
        this.levelChoosePopWindow.active = false;
        this.chooseMode.active = true;
    }
    // 切换到游戏场景
    // 竞速模式，还没有写，暂时跳到闯关。
    competeSpeedMode() {
        if (this.tapaudio) cc.audioEngine.playEffect(this.tapaudio, false);
        cc.audioEngine.stopMusic();
        global.gameMode = 1;
        cc.director.loadScene("Game - 002");
    }

    /**
     * 进入游戏
     */
    enterGame() {
        cc.audioEngine.stopMusic();
        global.gameMode = 0;
        cc.director.loadScene("Game - 002");
    }

    /**
     * 加载排行榜场景
     */
    loadLRScene() {
        if (this.tapaudio) cc.audioEngine.playEffect(this.tapaudio, false);
        cc.audioEngine.stopMusic();
        cc.director.loadScene("Leaderboard");
    }

    /**
     * 显示选关弹窗
     */
    setChooseLevelView() {
        for (let i = 0; i < config.allBreakingMapNum; i++) {
            let tempNode = this.chooseLayout.node.children[i];
            if (!tempNode) {
                tempNode = cc.instantiate(this.levelChoosePrefab);
                tempNode.setParent(this.chooseLayout.node);
            }
            if (i <= global.maxBreakingLevel) {
                tempNode.getComponentInChildren(cc.Label).string = (i + 1).toString();
                let tempButton = tempNode.getComponent(cc.Button);
                tempButton.node.on(cc.Node.EventType.TOUCH_START, (event) => {
                    global.nowBreakingLevel = i;
                    this.enterGame();
                })
            }
            else {
                tempNode.getComponentInChildren(cc.Label).string = '?';
            }
        }
        this.levelChoosePopWindow.active = true;
    }

    /**
     * 显示‘开始游戏’和‘排行榜’按钮
     */
    buttonOn() {
        this.startGameButton.node.active = true;
        this.leaderboardButton.node.active = true;
    }

    /**
     * 关闭‘开始游戏’和‘排行榜’按钮
     */
    buttonOff() {
        this.startGameButton.node.active = false;
        this.leaderboardButton.node.active = false;
    }

    /**
     * 设置当前组件的图片,目前只支持用url远程获取
     * @param url 图片的url
     */
    setPhoto(url: string, nowSprite: cc.Sprite, type: string) {//加载url内的图片作为飞行物显示出来
        cc.assetManager.loadRemote(url, { ext: type }, (err, texture) => {
            let temWidth = nowSprite.node.width;
            let temheight = nowSprite.node.height;
            nowSprite.spriteFrame = new cc.SpriteFrame(texture); // 传入图片
            nowSprite.node.width = temWidth;          // 将图片形状还原到原本大小
            nowSprite.node.height = temheight;
        });
    }

    /**
     * 提供微信的游戏分享
     */
    enableShareButton() {
        wx.showShareMenu({ withShareTicket: true, menus: ['shareAppMessage', 'shareTimeline'] });
        wx.onShareAppMessage(() => {
            return {
                title: "一起来太空点击吧！",
                imageUrl: config.shareToFriendURL
            }
        });
        wx.onShareTimeline(() => {
            return {
                title: "一起来太空点击吧！",
                imageUrl: config.shareToTimelineURL
            }
        });
    }
}

/**
 * 获取玩家的信息权限
 */
export function getAuth(size): void {
    let getUserInfoButton = wx.createUserInfoButton({
        type: 'text',
        text: '微信授权登录',
        style: {
            left: size.width / 2 - 200 * size.width / 720,
            top: 900 * size.height / 1280,
            width: 400 * size.width / 720,
            height: 100 * size.height / 1280,
            lineHeight: 100 * size.height / 1280,
            backgroundColor: '#DFE6E9',
            color: '#2D3436',
            textAlign: 'center',
            fontSize: 50 * size.height / 1280,
            borderRadius: 10 * size.height / 1280
        }
    })
    getUserInfoButton.onTap((res) => {
        // console.log("用户开始授权");
        if (res.userInfo) {
            wx.showToast({ title: "授权成功" });
            Util.initCloud();
            cc.find("Canvas").getComponent("Home").buttonOn();
            getUserInfoButton.hide();
            pushPlayerInfo();
        }
        else {
            wx.showToast({ title: "授权失败" });
        }
    })
}

/**
 * 获取玩家的基础信息
 */
export function getPlayerInfo(size) {
    // console.log("开始读取信息");
    wx.getSetting({
        success: (res) => {
            if (res.authSetting['scope.userInfo']) {
                cc.find("Canvas").getComponent("Home").buttonOn();
                pushPlayerInfo();
                Util.initCloud();
            }
            else {
                // console.log("noAuth");
                getAuth(size);
            }
        },
        fail: () => { /*console.log("fail")*/; getAuth(size) },
        complete: () => null,
    })
}

/**
 * 将用户信息导入组件中
 */
export function pushPlayerInfo() {
    wx.getUserInfo
        ({
            success: function (res) {
                cc.log(res.userInfo);
                var userInfo = res.userInfo
                let playerNode = !!cc.find("Canvas") && !!cc.find("Canvas").getComponent("Home") ? cc.find("Canvas").getComponent("Home").playerNode : null;
                const playerInfo: PlayerInfos =
                {
                    nickname: userInfo.nickName,
                    avatar: userInfo.avatarUrl,
                    gender: userInfo.gender,
                }
                global.player = playerInfo;
                !!playerNode && playerNode.loadingInfo();
                // !!playerNode && playerNode.getInfo(playerInfo, true);
            }
        });
}


/**
 * 判断是否获得相应权限
 * @param scope
 */
export function isAuth(scope?: string): boolean {
    let flag = false;
    const sc = scope ? scope : 'scope.userInfo';
    wx.getSetting({
        success: (res) => {
            flag = res.authSetting[scope]
        },
        fail: () => null,
        complete: () => null,
    })
    return flag;
}
